<script setup>

import { ref,reactive,onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage  } from 'element-plus'; // 使用 Element Plus 的 message 组件
import axios from 'axios'
import { userStore } from '@/store/index.js'
const userItemStore = userStore();


const router = useRouter();
const refLoginForm = ref(null); // 创建一个 ref 来引用 el-form
const isButtonDisabled = ref(false);
const codeUrl = ref('');
const loginForm = reactive({
  account: '',
  password: '',
  code: '1234',
  key: '',
});

const rules = reactive({
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '长度必须是4位', trigger: 'blur' }
  ]
});

const userLogin = () => {
  // 验证表单
  // const formRef = loginForm.value;
  // 发起登录请求
  refLoginForm.value.validate(valid => {
    if (valid) {
      axios.post('/user/login', loginForm).then(resp => {
        const user = resp.data;
        // 这里响应头大小写敏感，要写成小写
        localStorage.setItem('token', resp.headers.authorization);
        // 保存用户信息，转成字符串保存
        localStorage.setItem('user', JSON.stringify(user));

        //存储用户
        userItemStore.updateUser(user)
        console.log(user)
        //修改状态
        userItemStore.updateLoginStatus(true)

        // 提示登录成功
        ElMessage({
          message:`登录成功，欢迎您：${user.account}！`,
          type:'success'
        });
        // 跳转到首页
        router.push('/');
      }).catch(error => {
        // 登录失败
        const messageText = error.response.data;
        ElMessage.error(`登录失败，${messageText}`);
      });
    } else {
      return false;
    }
  });
}

onMounted(()=>{
  //获取验证码
  getCaptcha()
})
//获取验证码
const getCaptcha = ()=>{
  axios.get('/user/code').then(resp => {
    //返回两个数据：key是Redis中key，base64Img是图片
    codeUrl.value = resp.data.base64Img;
    loginForm.key = resp.data.key;
  })
}

////////////////////////////////////////////////////////////////
/////////////////////////////手机号登录///////////////////////////
////////////////////////////////////////////////////////////////
const activeName =ref('telephone');   //默认激活的tab
const refSmsForm = ref(null);
const smsForm = reactive({
  telephone: '18665591009',
  code: '1234'
});

const rulesPhone = reactive({
  telephone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '长度必须是4位', trigger: 'blur' }
  ]
})
const smsDisabled = ref(false);  //发短信按钮是否可用
const smsText =ref('发送短信验证码');
//获取短信
const sendSms = ()=>{
  //验证手机号是否正确
  refSmsForm.value.validateField('telephone', error => {
    //如果没有错误，则验证通过
    if (error) {
        smsDisabled.value = true;
        axios.get(`/user/sendSms/${smsForm.telephone}`).then(resp => {
          //发送成功
          ElMessage({message:resp.data,type:'success'});
        }).catch(error => {
          //发送失败
          ElMessage.error(error.response.data);
        }).finally(() => {
          //按钮文字变成倒计时
          let seconds = 15;
          smsText.value = `${seconds}秒后重新发送`;
          let timer = setInterval(() => {
            seconds--;
            if (seconds > 0) {
              smsText.value = `${seconds}秒后重新发送`;
            } else {
              //修改文字
              smsText.value = "发送短信验证码";
              //按钮可用
              smsDisabled.value = false;
              //清除定时器
              clearInterval(timer);
            }
          }, 1000);
        });
    }
  });
}

//短信登录
const smsLogin = ()=>{
  refSmsForm.value.validate(valid=>{
    if (valid){
      //编写登录逻辑
      axios.post('/user/smsLogin', smsForm).then(resp => {
        //获取到User对象
        const user = resp.data;
        //登录成功
        ElMessage({
          message:`登录成功，欢迎您：${user.account}`,
          type:'success'
        });
        //将后端返回的用户登录信息保存到store中
        userItemStore.updateUser(user)
        userItemStore.updateLoginStatus(true)

        //保存用户信息到本地浏览器中
        localStorage.setItem("user", JSON.stringify(user));
        //这里必须是小写
        localStorage.setItem("token", resp.headers['authorization']);
        //登录成功后跳转
        router.push('/');
      }).catch(error => {
        //登录失败
        ElMessage.error('登录失败，' + error.response.data);
      });
    }else{
      return false;
    }
  })
}

</script>

<template>
  <div class="login-container">

    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="用户名登录" name="userName">
        <el-card class="card">
          <h2 class="title">蜗牛书城用户登录</h2>
          <el-form ref="refLoginForm" :model="loginForm"
                   class="login-form"
                   :rules="rules" label-position="left"
                   label-width="80px">
            <el-form-item label="用户名：" prop="account">
              <el-input v-model="loginForm.account" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input type="password"
                        v-model="loginForm.password"
                        placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="验证码：" prop="code">
              <div class="form-item-container">
                <el-input v-model="loginForm.code"
                          maxlength="4"
                          minlength="4"
                          placeholder="验证码"
                          style="width: 90px;">
                </el-input>
                <img :src="codeUrl"
                     style="cursor: pointer; margin-left: 10px;"
                     @click="getCaptcha()"
                     title="看不清点击刷新"/>
              </div>
            </el-form-item>
            <div class="login-btn-container">
              <el-button style="width: 150px;" type="primary"
                         @click="userLogin"
                         :disabled="isButtonDisabled"
                         icon="el-icon-user-solid">登录
              </el-button>
            </div>
          </el-form>
        </el-card>

      </el-tab-pane>

      <!-- 手机号登录 -->
      <el-tab-pane class="container" label="手机号登录" name="telephone">
        <el-card class="card">
          <h2 class="title">蜗牛书城用户登录</h2>
        <el-form ref="refSmsForm" :model="smsForm"
                 class="login-form" :rules="rulesPhone"
                 label-position="left"
                 label-width="80px">
          <el-form-item label="手机号：" prop="telephone">
            <el-input v-model="smsForm.telephone"
                      placeholder="请输入手机号">
              <template #suffix>
                <el-icon><Iphone /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码：" prop="code">
            <div class="form-item-container">
              <el-input v-model="smsForm.code" maxlength="4"
                        minlength="4" placeholder="验证码"
                        style="width: 90px; margin-right: 10px;">
              </el-input>
              <el-button type="text" :disabled="smsDisabled"
                         @click="sendSms">
                <el-icon :size="20"><Message /></el-icon>
                {{smsText }}
              </el-button>
            </div>
          </el-form-item>
          <div class="login-btn-container">
            <el-button style="width: 150px;"
                       type="primary" @click="smsLogin"
                       icon="el-icon-user-solid">登录
            </el-button>
          </div>
        </el-form>
        </el-card>
      </el-tab-pane>


    </el-tabs>
  </div>
</template>

<style scoped>
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  left: 0;
  background-image: linear-gradient(0, rgb(68, 68, 235), lightblue);
  display: flex;
  /* 水平居中对齐 */
  justify-content: center;
  /* 垂直居中对齐 */
  height: 100%;
}

.card {
  margin-top: 20px;
  width: 450px;
  height: 430px;
  padding: 15px;
}

.title {
  margin-top: 10px;
  font-size: 25px;
  text-shadow: 2px 2px 4px #888;
  text-align: center;
}

.login-form {
  max-width: 300px;
  margin: 0 auto;
}

.login-btn-container {
  text-align: center;
  margin-bottom: 30px;
}

.form-item-container {
  display: flex;
  align-items: flex-end;
}
</style>
